<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>31.构造函数与class语法糖中使用访问器</title>
</head>

<body>
  <script>

    // 构造函数
    function User1 (name, age) {
      let data = { name, age };
      Object.defineProperties(this, {
        name: {
          set (name) {
            if (name.trim() == "" || name.length > 20) {
              throw new Error("用户名不合法");
            }
            data.name = name;
          },
          get () {
            return data.name;
          },
        },
        age: {
          set (age) {
            data.age = age;
          },
          get () {
            return data.age;
          },
        }
      });
    }

    let user1 = new User1("lisi", 19);
    user1.name = '张三';
    user1.age = 22;
    console.log(user1.name, user1.age);


    // class 语法糖
    // 私有化属性
    const DATA = Symbol();
    class User2 {
      constructor(name, age) {
        this[DATA] = { name, age }
      }
      set name (name) {
        if (name.trim() == "" || name.length > 20) {
          throw new Error("用户名不合法");
        }
        this[DATA].name = name;
      }
      get name() {
        return this[DATA].name;
      }
      set age(age) {
        this[DATA].age = age;
      }
      get age () {
        return this[DATA].age;
      }

    }

    let user2 = new User2("lisi", 19);
    user2.name = '张三2';
    user1.age = 222;
    console.log(user2.name, user2.age);
  </script>
</body>

</html>